<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/2/5
 * Time: 14:36
 */

namespace AppApi\Controller;


use Common\Model\AddressModel;
use Common\Model\MemberModel;
use Common\Model\MemChainModel;
use Common\Model\SystemMsgModel;
use System\Model\SmsModel;

class MemberController extends ApiBaseController
{
    private $member_model;
    private $sms_model;
    private $system_msg_model;
    private $address_model;

    public function __construct()
    {
        parent::__construct();
        $this->member_model     = new MemberModel();
        $this->sms_model        = new SmsModel();
        $this->system_msg_model = new SystemMsgModel();
        $this->address_model    = new AddressModel();
    }

    /**
     * 发送短信验证码
     */
    public function sendSms() {
        if(!IS_POST) {
            exit($this->returnApiError(ApiBaseController::INVALID_INTERFACE));
        }

        $username = I('post.username');
        $type = I('post.type');
        $this->checkparam(['手机号'=> $username, '类型' => $type]);

        if($type == SmsModel::TYPE_1) {
            if($this->member_model->checkUserName($username) > 0) {
                exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '该账号已注册'));
            }
        } else if($type == SmsModel::TYPE_2 || $type == SmsModel::TYPE_3) {
            if($this->member_model->checkUserName($username) != 1) {
                exit($this->returnApiError(ApiBaseController::FATAL_ERROR,'未找到该账号'));
            }
        }

        $code = get_code(6, 1);
        $content = '【'.C('SMS_ACCOUNT.company').'】你的验证码是:' . $code . '，15分钟内有效。';

        if (strlen($username) != 11)
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '手机号码错误'));

        $result = set_phone($username,'尊敬的用户，您的验证码是:'.$code.'，15分钟内有效。');

        if (!$result) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '验证码发送失败'));
        }

        if (!$this->sms_model->add_row($code, $content, $username, $type)) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '写入失败'));
        }

        exit($this->returnApiSuccess());
    }

    /**
     * 注册
     */
    public function register() {
        if (!IS_POST) exit($this->returnApiError(ApibaseController::INVALID_INTERFACE));

        $username   = I('post.username');
        $password   = I('post.password');
        $code       = I('post.code');
        $phone      = I('post.phone');
        $sex        = I('post.sex');
        $pwd2       = I('post.pwd2');
        $nickname   = I('post.nickname');
        $city       = I('post.city');
        $address    = I('post.address');
        $birthday   = I('post.birthday');


//        dump($_POST);exit;
        $this->checkparam(['密码' => $password, '验证码' => $code, '用户名' => $username]);

        if($password != $pwd2) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '两次密码输入不一致'));
        }

        if ($this->member_model->checkUserName($phone) > 0) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '该手机号已注册'));
        }


        if (!$this->sms_model->checkCode($phone, $code, SmsModel::TYPE_1)) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '验证码错误或过期'));
        }

        $data = [
            'username'      => $username,
            'password'      => sp_password($password),
            'phone'         => $phone,
            'sex'           => $sex,
            'nickname'      => $nickname,
            'city'          => $city,
            'address'       => $address,
            'birthday'      => $birthday,
            'create_time'   => date('Y-m-d H:i:s', time()),
            'update_time'   => date('Y-m-d H:i:s', time()),
        ];
        $mid = $this->member_model->add($data);
        if ($mid == false) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '注册失败'));
        }
        $city = explode('-', $city);
        $data_address = [
            'province'  => $city[0],
            'city'      => $city[1],
            'country'   => $city[2],
            'address'   => $address,
            'fullname'  => $nickname,
            'mid'       => $mid,
            'phone'     => $phone
        ];
        if($this->address_model->add($data_address) == false) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '注册失败'));
        }


        exit($this->returnApiSuccess());
    }

    /**
     * 修改登录密码
     */
    public function modifyPwd() {
        if (!IS_POST) exit($this->returnApiError(ApibaseController::INVALID_INTERFACE));

        $username = I('post.username');
        $oldPwd = I('post.oldPwd');
        $newPwd = I('post.newPwd');
        //
        $this->checkparam([$username, $newPwd, $oldPwd]);
        if($oldPwd == $newPwd) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '不能与原密码相同'));
        }
        $where = ['username' => $username];
        $member = $this->member_model->where($where)->find();
        if (!$member)
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '用户不存在'));

        if (!sp_compare_password($oldPwd, $member['password']))
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '旧密码错误'));

        if (strlen($newPwd) < 6) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '密码长度过短'));
        }
        $resutl = $this->member_model->where($where)->save(['password' => sp_password($newPwd)]);
        if ($resutl === false) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '密码修改失败'));
        }

        exit($this->returnApiSuccess());
    }

    /**
     * 找回密码
     */
    public function backPassword()
    {
        if (!IS_POST) exit($this->returnApiError(ApibaseController::INVALID_INTERFACE));

        $username   = I('post.username');
        $code       = I('post.code');
        $password   = I('post.password');

        $this->checkparam([$username, $code, $password]);
        if (strlen($password) < 6)
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '密码长度过短'));

        $where = ['phone' => $username];
        $member = $this->member_model->where($where)->find();

        if (!$member) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '查无此用户'));
        }

        $result = $this->sms_model->checkcode($username, $code, SmsModel::TYPE_2);
        if (!$result) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '验证码错误或过期'));
        }

        $update = $this->member_model->where($where)->save(['password' => sp_password($password)]);

        if ($update === false) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '密码修改失败'));
        }

        exit($this->returnApiSuccess());
    }

    /**
     * 用户登录
     */
    public function userLogin() {
        if (!IS_POST)
            exit($this->returnApiError(ApibaseController::INVALID_INTERFACE));

        $userAccount = I("post.userAccount");
        $userPassword = I("post.userPassword");
        $this->checkparam([$userAccount, $userPassword]);

        $where = [
            'username' => $userAccount,
            'password' => sp_password($userPassword),
        ];
        $field = 'id as mid, username,header, mem_level, nickname';
        $members = $this->member_model
            ->field($field)
            ->where($where)
            ->find();

        if (!$members) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '帐号或者密码错误'));
        }

        $members['header'] = setUrl($members['header']);

        $token = $this->createtoken();
        $token_time_out = time() + 3600 * 24 * 7;
        $save_result = $this->member_model->where(['id' => $members['mid']])->save(
            [
                'token'          => $token,
                'token_time_out' => $token_time_out,
                'ip'             => get_client_ip(),
            ]);

        $members['token'] = $token;

        if ($save_result === false) {
            exit($this->returnApiError(ApibaseController::FATAL_ERROR, '登录错误'));
        }

        exit($this->returnApiSuccess($members));
    }

    /**
     * 退出登录
     */
    public function userLoginOut()
    {
        if (!IS_POST) exit($this->returnApiError(ApibaseController::INVALID_INTERFACE));

        $mid = I('post.mid');
        $this->checkparam([$mid]);

        $result = $this->member_model
            ->where(['id' => $mid])
            ->save([
                'token'          => '',
                'token_time_out' => '',
            ]);
        if ($result === false) exit($this->returnApiError(ApibaseController::FATAL_ERROR));
        exit($this->returnApiSuccess());
    }

    public function test() {
//        $this->member_model->checkFirstBuy(1);
        $this->mem_chain_model->dealLevel();
    }




}